<template>
  <div>
        <!-- 搜索栏 -->
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="图书名称">
              <el-input v-model="formInline.name" placeholder="请输入图书名称"></el-input>
            </el-form-item>
            <el-form-item label="图书类别">
              <el-select v-model="formInline.categoryName" placeholder="请输入图书类别">
              <el-option
                v-for="item in options"
                :key="item.id"
                :value="item.type">
              </el-option>
              </el-select>
            </el-form-item>
            <!-- 开始时间 -->
            <el-form-item class="block">
              <span class="demonstration">创建时间</span>
              <el-date-picker
                v-model="formInline.begin"
                type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
        <!-- 结束时间 -->
            <el-form-item class="block">
              <span class="demonstration">创建时间</span>
              <el-date-picker
                v-model="formInline.end"
                type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="onSubmit" class="el-icon-search">查询</el-button>
              <!-- 新增图书 -->
              <el-button type="primary" @click="openAddWindow()" class="addButton el-icon-plus">新增图书</el-button>
            </el-form-item>
    </el-form>

    <!-- 主体表格 -->
    <el-table :data="bookList" style="width: 100%" class="table" border>
      <el-table-column prop="name" label="图书名称" width="150"></el-table-column>
      <el-table-column prop="categoryName" label="图书类别" width="150"></el-table-column>
      <el-table-column prop="author" label="作者" width="150"></el-table-column>
      <el-table-column  label="单价(￥)" width="150">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="库存(本)" width="150"></el-table-column>
      <el-table-column label="简介" width="150">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showDetail(scope.row)" class="el-icon-question">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="150"></el-table-column>
      <el-table-column prop="updateTime" label="修改时间" width="150"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" @click="del(scope.row)" class="el-icon-delete" size="mini">删除</el-button>
          <el-button type="primary" @click="openUpdateWindow(scope.row)" class="el-icon-edit" size="mini">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
  <div class="block">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[5, 8, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>

  <!-- 详情表单 -->
  <el-dialog title="图书详情" :visible.sync="dialogFormVisible">
  <el-form :model="book">
    <el-form-item label="图书名称" :label-width="formLabelWidth">
      <el-input v-model="book.name" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="图书类别" :label-width="formLabelWidth">
      <el-input v-model="book.categoryName" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="作者" :label-width="formLabelWidth">
      <el-input v-model="book.author" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="单价" :label-width="formLabelWidth">
      <el-input v-model="book.price" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="库存" :label-width="formLabelWidth">
      <el-input v-model="book.quantity" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="简介" :label-width="formLabelWidth">
      <el-input type="textarea" v-model="book.description"></el-input>
    </el-form-item>
    <el-form-item label="创建时间" :label-width="formLabelWidth">
      <el-input v-model="book.createTime" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="修改时间" :label-width="formLabelWidth">
      <el-input v-model="book.updateTime" autocomplete="off"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
  </div>
</el-dialog>

<!-- 新增图书表单 -->
  <el-dialog title="新增图书" :visible.sync="dialog4FormVisible">
  <el-form :model="addBookValue">
    <el-form-item label="图书名称" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.name" autocomplete="off"></el-input>
    </el-form-item>
        <el-form-item label="图书类别" :label-width="formLabelWidth">
      <el-select v-model="addBookValue.categoryName" autocomplete="off">
        <el-option
          v-for="item in options"
          :key="item.id"
          :value="item.type">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="作者" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.author" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="单价" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.price" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="库存" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.quantity" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="简介" :label-width="formLabelWidth">
      <el-input type="textarea" v-model="addBookValue.description"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialog4FormVisible = false">取 消</el-button>
    <el-button type="primary" @click="addBook">确 定</el-button>
  </div>
</el-dialog>

<!-- 编辑图书表单 -->
  <el-dialog title="编辑图书" :visible.sync="dialogUpdateFormVisible">
  <el-form :model="addBookValue">
    <el-form-item label="图书名称" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.name" autocomplete="off"></el-input>
    </el-form-item>
        <el-form-item label="图书类别" :label-width="formLabelWidth">
      <el-select v-model="addBookValue.categoryName" autocomplete="off">
        <el-option
          v-for="item in options"
          :key="item.id"
          :value="item.type">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="作者" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.author" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="单价" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.price" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="库存" :label-width="formLabelWidth">
      <el-input v-model="addBookValue.quantity" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="简介" :label-width="formLabelWidth">
      <el-input type="textarea" v-model="addBookValue.description"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="dialogUpdateFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="updateBook">确 定</el-button>
  </div>
</el-dialog>

  </div>
</template>
<script>
import { deleteBookById, bookListPage, getById, addBook, updateById } from '@/api/book.js'
import { getAllCategory } from '@/api/category.js'
export default {
  name: 'BookPage',
  data () {
    return {
      bookList: [],
      page: 1, // 当前页码
      pageSize: 5, // 当前页展示记录数
      total: null,
      book: {},
      dialogFormVisible: false, // 查看简介窗口
      formLabelWidth: '120px',
      dialog4FormVisible: false, // 新增图书窗口
      addBookValue: { // 新增图书
        id: '',
        categoryName: '', // 下拉框选择的分类
        name: '',
        author: '',
        quantity: '',
        description: '',
        price: null
      },
      options: [], // 存放请求回来的分类数据，用于页面渲染分类
      dialogUpdateFormVisible: false, // 编辑窗口
      formInline: { // 条件查询框数据
        name: null,
        categoryName: null,
        begin: null,
        end: null
      }

    }
  },
  async created () {
    this.getPageBookList()
    const { data } = await getAllCategory()
    this.options = data
  },
  methods: {
    // 处理日期数据为"yyyy-MM-dd HH:mm:ss""
    handleDate (dateString) {
      // 设置时区，假设我们希望得到的是 UTC 时间
      const date = new Date(dateString)
      date.setUTCHours(0, 0, 0, 0) // 第一个参数是小时，后续参数分别是分钟、秒、毫秒

      // 获取年月日以零填充的两位数
      const year = date.getUTCFullYear()
      const month = (`0${date.getUTCMonth() + 1}`).slice(-2)
      const day = (`0${date.getUTCDate()}`).slice(-2)
      // 获取时间部分，注意这里我们使用了 T 分隔符
      const hours = (`0${date.getUTCHours()}`).slice(-2)
      const minutes = (`0${date.getUTCMinutes()}`).slice(-2)
      const seconds = (`0${date.getUTCSeconds()}`).slice(-2)
      // 合并日期和时间，返回最终的字符串
      const newDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      return newDate
    },
    async onSubmit () {
      // 判断是否输入了时间，如果没输入的话进行格式转化，会将数据传递到后端然后报错
      // console.log(this.formInline.begin)
      // console.log(this.formInline.end)
      // if (this.formInline.begin && this.formInline.end) {
      //   this.formInline.begin = this.handleDate(this.formInline.begin)
      //   this.formInline.end = this.handleDate(this.formInline.end)
      // }
      const res = await bookListPage(this.page, this.pageSize, this.formInline.name, this.formInline.categoryName,
        this.formInline.begin, this.formInline.end)
      this.bookList = res.data.records
      this.total = res.data.total
      console.log(res)
    },

    // 编辑图书
    async updateBook () {
      const res = await updateById(this.addBookValue.id, this.addBookValue.name, this.addBookValue.categoryName, this.addBookValue.author,
        this.addBookValue.price, this.addBookValue.quantity, this.addBookValue.description)
      console.log(res)
      this.$message({
        type: 'success',
        message: '修改成功'
      })
      this.getPageBookList()
      this.dialogUpdateFormVisible = false
    },

    // 打开编辑窗口
    async openUpdateWindow (row) {
      this.dialogUpdateFormVisible = true
      // 根据id查询图书数据，回显到编辑窗口
      const { data } = await getAllCategory() // 查询分类信息
      this.options = data
      const res = await getById(row.id) // 根据id查询图书信息
      this.addBookValue = res.data
    },

    // 打开新增窗口
    async openAddWindow () {
      this.addBookValue = {}
      this.dialog4FormVisible = true
      const { data } = await getAllCategory()
      this.options = data
    },

    // 新增图书
    async addBook () {
      const res = await addBook(this.addBookValue.name, this.addBookValue.categoryName, this.addBookValue.author,
        this.addBookValue.price, this.addBookValue.quantity, this.addBookValue.description)
      console.log(res)
      this.$message({
        type: 'success',
        message: '添加成功'
      })
      this.addBookValue = {}
      this.getPageBookList()
      this.dialog4FormVisible = !this.dialog4FormVisible
    },

    // 根据id获取图书信息
    async showDetail (row) {
      this.dialogFormVisible = !this.dialogFormVisible
      const res = await getById(row.id)
      this.book = res.data
    },

    // 分页获取图书信息
    async getPageBookList () {
      const { data } = await bookListPage(this.page, this.pageSize, this.formInline.name, this.formInline.categoryName,
        this.formInline.begin, this.formInline.end)
      this.bookList = data.records
      this.total = data.total
    },

    // 删除图书
    del (row) {
      console.log(row)
      this.$confirm('确定要将本书删掉吗?删除后将无法恢复!', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'

      }).then(async () => {
        await deleteBookById(row.id)
        this.getPageBookList() // 刷新图书列表
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },

    // 每页条数改变时触发
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.getPageBookList()
    },

    // 当前页码改变时触发
    handleCurrentChange (page) {
      this.page = page
      // 调用分页查询
      this.getPageBookList()
    }
  }

}
</script>

<style lang="less">
.input {
  width: 200px;
  text-align: center;
}

.addButton {
  text-align: right;
}
</style>
